package com.lsj.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lsj.config.redis.RedisKey;
import com.lsj.core.lock.DistributedLock;
import com.lsj.core.lock.LockKey;
import com.lsj.core.util.QueryHelperUtil;
import com.lsj.dto.sys.RoleDto;
import com.lsj.dto.sys.UserRoleDto;
import com.lsj.mapper.MySysRoleMapper;
import com.lsj.mapper.SysUserRoleMapper;
import com.lsj.mapper.entity.SysRole;
import com.lsj.mapper.entity.SysUserRole;
import com.lsj.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:lin.sj
 * @Data:2021/7/8 19:37
 * @Desc:
 */
@Service
@CacheConfig(cacheNames = RedisKey.USER_KEY)
public class UserRoleServiceImpl  implements UserRoleService {
    @Autowired
    SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    MySysRoleMapper mySysRoleMapper;

    /**
     * @Author: lin.sj
     * @Date: 2021/8/18 20:22
     * @Desc: 为用户更新角色，更新完毕后，需要从redis中去除用户加载的信息(因为权限变了)
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(key = "#dto.account")
    @DistributedLock(value = LockKey.org_tree_key)
    public void updateRoleForUser(UserRoleDto dto) {
        LambdaQueryWrapper<SysUserRole> w = QueryHelperUtil.getLambdaWrapper(SysUserRole.class);
        w.eq(SysUserRole::getUserId,dto.getUserId());
        sysUserRoleMapper.delete(w);
        List<Long> roleIds = dto.getRoleIds();
        if(roleIds !=null && roleIds.size() >0){
            roleIds.stream().forEach(r -> {
                SysUserRole userRole = new SysUserRole().setUserId(dto.getUserId()).setRoleId(r);
                sysUserRoleMapper.insert(userRole);
            });
        }
    }

    /**
     * @Author: lin.sj
     * @Date: 2021/8/18 20:22
     * @Desc: 根据用户获取关联的角色
     **/
    @Override
    public List<RoleDto> findRoleByUserId(Long userId) {
        List<SysRole> roles = mySysRoleMapper.findRoleByUserId(userId);
        List<RoleDto> roleDtos = roles.stream().map(r -> {
            return Convert.convert(RoleDto.class, r);
        }).collect(Collectors.toList());
        return roleDtos;
    }
}
